package com.arsn.myf.system.service.impl;

import com.arsn.myf.common.exception.ExcelException;
import com.arsn.myf.common.exception.ServiceException;
import com.arsn.myf.common.util.StringUtils;
import com.arsn.myf.common.util.auth.AuthUtil;
import com.arsn.myf.common.util.excel.ExcelUtil;
import com.arsn.myf.system.entity.*;
import com.arsn.myf.system.excel.UserExcel;
import com.arsn.myf.system.mapper.UserMapper;
import com.arsn.myf.system.service.DeptService;
import com.arsn.myf.system.service.UserPostService;
import com.arsn.myf.system.service.UserRoleService;
import com.arsn.myf.system.service.UserService;
import com.arsn.myf.system.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.datical.liquibase.ext.checks.config.IFileAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户实现层
 * @author zhongrj
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserPostService userPostService;

    @Autowired
    private DeptService deptService;

    /**
     * 自定义查询用户分页数据
     * @param page
     * @param user
     * @return
     */
    @Override
    public IPage<UserVO> selectPageUserList(Page<UserVO> page, UserVO user) {
        return baseMapper.selectPageUserList(page,user);
    }

    /**
     * 用户新增
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(User user) {
        //账户校验（唯一）
        boolean flag = checkAccount(user.getAccount());
        if (flag){
            throw new ServiceException("账户名："+user.getAccount()+ "已存在!");
        }
        //用户新增
        boolean save = this.save(user);
        if (save) {
            //角色，岗位处理
            //角色处理
            List<String> roleIdList = Arrays.asList(user.getRoleId());
            for (String roleId : roleIdList) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(Long.parseLong(roleId));
                // 新增
                userRoleService.save(userRole);
            }

            //岗位处理
            List<String> postIdList = Arrays.asList(user.getPostId());
            for (String postId : postIdList) {
                UserPost userPost = new UserPost();
                userPost.setUserId(user.getId());
                userPost.setPostId(Long.parseLong(postId));
                // 新增
                userPostService.save(userPost);
            }
        }
        //返回
        return true;
    }

    /**
     * 账户唯一检查
     * @param account 账户名
     * @return
     */
    private boolean checkAccount(String account) {
        return baseMapper.checkAccount(account)>0?true:false;
    }

    /**
     * 用户信息修改
     * @param user 用户对象信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        user.setUpdateTime(new Date());
        //更新用户信息
        this.updateById(user);
        //更新角色，岗位信息
        updateUserRole(user);
        updateUserPost(user);
        //返回
        return true;
    }

    /**
     * 更新用户岗位关联信息
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserPost(User user) {
        //查询用户岗位关联信息
        UserPost userPost = new UserPost();
        userPost.setUserId(user.getId());
        List<UserPost> userPostList = userPostService.list(new QueryWrapper<>(userPost));
        if (userPostList.size()>0) {
            //转换
            List<Long> userPostIdList = userPostList.stream().map(UserPost::getPostId).collect(Collectors.toList());
            List<String> postIdLists = Arrays.asList(user.getPostId().split(","));
            List<Long> postIdList = postIdLists.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
            //比较
            List<Long> addPostIdList = postIdList.stream().filter(a -> userPostIdList.contains(a)).collect(Collectors.toList());
            List<Long> removePostIdList = userPostIdList.stream().filter(a -> postIdList.contains(a)).collect(Collectors.toList());
            if (addPostIdList.size() > 0) {
                //新增
                for (Long postId : addPostIdList) {
                    UserPost addUserPost = new UserPost();
                    addUserPost.setUserId(user.getId());
                    addUserPost.setPostId(postId);
                    // 新增
                    userPostService.save(addUserPost);
                }
            }
            if (removePostIdList.size() > 0) {
                //删除
                for (Long postId : removePostIdList) {
                    QueryWrapper<UserPost> wrapper = new QueryWrapper<>();
                    wrapper.eq("post_id", postId).eq("user_id", user.getId());
                    userPostService.remove(wrapper);
                }
            }
        }else {
            //转换
            List<String> postIdLists = Arrays.asList(user.getPostId().split(","));
            List<Long> postIdList = postIdLists.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
            //新增
            for (Long postId : postIdList) {
                UserPost addUserPost = new UserPost();
                addUserPost.setUserId(user.getId());
                addUserPost.setPostId(postId);
                // 新增
                userPostService.save(addUserPost);
            }
        }
    }

    /**
     * 更新用户角色关联信息
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(User user) {
        //查询用户角色信息
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<>(userRole));
        if (userRoleList.size()>0) {
            //转换
            List<Long> userRoleIdList = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            List<String> roleIdLists = Arrays.asList(user.getRoleId().split(","));
            List<Long> roleIdList = roleIdLists.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
            //比较
            List<Long> addRoleIdList = roleIdList.stream().filter(a -> !userRoleIdList.contains(a)).collect(Collectors.toList());
            List<Long> removeRoleIdList = userRoleIdList.stream().filter(a -> !roleIdList.contains(a)).collect(Collectors.toList());
            if (addRoleIdList.size() > 0) {
                //新增
                for (Long roleId : addRoleIdList) {
                    UserRole addUserRole = new UserRole();
                    addUserRole.setUserId(user.getId());
                    addUserRole.setRoleId(roleId);
                    // 新增
                    userRoleService.save(addUserRole);
                }
            }
            if (removeRoleIdList.size() > 0) {
                //删除
                for (Long roleId : removeRoleIdList) {
                    QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
                    wrapper.eq("role_id", roleId).eq("user_id", user.getId());
                    userRoleService.remove(wrapper);
                }
            }
        }else {
            List<String> roleIdLists = Arrays.asList(user.getRoleId().split(","));
            List<Long> roleIdList = roleIdLists.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
            //新增
            for (Long roleId : roleIdList) {
                UserRole addUserRole = new UserRole();
                addUserRole.setUserId(user.getId());
                addUserRole.setRoleId(roleId);
                // 新增
                userRoleService.save(addUserRole);
            }
        }
    }

    /**
     * 根据用户查询权限集合
     * @param user 用户对象信息
     * @return
     */
    @Override
    public Set<String> getMenuPermission(User user) {
        return baseMapper.getMenuPermission(user);
    }

    /**
     * 根据用户查询角色集合
     * @param user 用户对象信息
     * @return
     */
    @Override
    public Set<String> getRolePermission(User user) {
        return baseMapper.getRolePermission(user);
    }

    /**
     * 查询所有用户
     * @param user
     * @return
     */
    @Override
    public List<UserVO> getUserList(UserVO user) {
        return baseMapper.getUserList(user);
    }

    /**
     * 根据用户ID查询角色信息
     * @param id 用户id
     * @return
     */
    @Override
    public List<Role> getRoleByUserId(Long id) {
        return baseMapper.getRoleByUserId(id);
    }

    /**
     * 用户密码修改
     * @param user(必须包含 id, password,newPassword)
     * @return
     */
    @Override
    public boolean updatePassword(UserVO user) {
        //查询数据库中的密码
        User user0 = this.getById(user.getId());
        //比对密码
        if (!new BCryptPasswordEncoder().matches(user.getPassword(),user0.getPassword())){
            return false;
        }
        //修改密码
        user0.setPassword(new BCryptPasswordEncoder().encode(user.getNewPassword()));
        user0.setUpdateTime(new Date());
        //更新用户信息
        boolean status = updateById(user0);
        //返回
        return status;
    }

    /**
     * 用户excel 导入
     * @param data
     * @param isCovered 是否覆盖
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importUser(List<UserExcel> data, Boolean isCovered) {
        List<User> userList = new ArrayList<>();
        User u = AuthUtil.getUser().getUser();
        Dept dept = deptService.getById(u.getDeptId());
        if (data.size()>0){
            data.forEach(userExcel -> {
                User user = new User();
                //部门信息比对
                if (!StringUtils.isBlank(userExcel.getDeptId())){
                    if (userExcel.getDeptId().equals(dept.getDeptName())){
                        user.setDeptId(dept.getId().toString());
                    }else {
                        throw new ServiceException(userExcel.getDeptId() + "名称不对应!");
                    }
                }
                if (!StringUtils.isBlank(userExcel.getRealName())){
                    user.setRealName(userExcel.getRealName());
                }
                if (!StringUtils.isBlank(userExcel.getNickName())){
                    user.setNickName(userExcel.getNickName());
                }
                if (!StringUtils.isBlank(userExcel.getSex())){
                    if (userExcel.getSex().contains("男")){
                        user.setSex(1);
                    }
                    if (userExcel.getSex().contains("女")){
                        user.setSex(2);
                    }
                }
                if (!StringUtils.isBlank(userExcel.getPhone())){
                    user.setPhone(userExcel.getPhone());
                    user.setAccount(userExcel.getPhone());
                }else {
                    throw new ServiceException("手机号不能为空!");
                }
                if (!StringUtils.isBlank(userExcel.getEmail())){
                    user.setEmail(userExcel.getEmail());
                }
                //加入集合
                userList.add(user);
            });
            //保存到数据库
            saveBatch(userList);
        }
    }

    /**
     * 查询用户导出数据
     * @param user
     * @return
     */
    @Override
    public List<UserExcel> exportUserExcelPage(UserVO user) {
        return baseMapper.getExportUserExcelPage(user);
    }
}

